/*
 * Copyright (c) 2020-2024 Huawei Cloud Computing Technology Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mqtt_client_entry.h"
#include "bmsinfo.h"
#include "common.h"
#include "iota_payload.h"


/**
 *
 * */
int ReportDeviceProperties(char *payload)
{
    int ret = -1;

    char *ptopic = MQTT_PUBTOPIC;
    ret = MqttTaskPublish(ptopic, payload); 
    return ret;
}

/**
 * @brief 
 * 
 * @param device_info_report 
 * @return HW_INT 
 */
HW_INT IOTA_ReportBmsInfoTabAll(ST_IOTA_DEVICE_INFO_REPORT *device_info_report)
{
    char *jsonroot = NULL;
    int messageId = -1;

    #if 0
    jsonroot = IOTA_ReportBmsInfoPayload(device_info_report);
    if (jsonroot == NULL)
    {
        return -1;
    }
    else
    {
        messageId = ReportDeviceProperties(jsonroot);
        if (jsonroot != NULL)
        {
            cJSON_free(jsonroot);
        }
    }

    #else // 
    // DebugMsg("[long] Start Report BmsInfo !\n");
    for (uint32_t i = 0;  i < getSizeOfListKey(); ++ i)
    {
        jsonroot = IOTA_ReportBmsInfoTabIndex(device_info_report, i);
        if (jsonroot == NULL)
        {
            break;
        }
        else
        {
            messageId = ReportDeviceProperties(jsonroot);
            if (messageId == 0)
            {
                // DebugMsg("\r[long] mqtt report msg ok ...\n");
            }
            else 
            {
                DebugMsg("\r[long] mqtt report msg failed ...\n");
            }

            if (jsonroot != NULL)
            {
                cJSON_free(jsonroot);
            }
            free(jsonroot);
        }

        osDelay(10);
    }
    #endif
    return messageId;
}


/**
 * @brief 
 * 
 */
void Mqtt_ReportBmsInfo_Handle(void)
{
    ST_IOTA_DEVICE_INFO_REPORT deviceInfo;
    char strline[32] = {0};
    if (!checkMqttConnectSt())   return;

    deviceInfo.device_sdk_version = SDK_VERSION;
    deviceInfo.sw_version = "v1.0";
    deviceInfo.fw_version = "v1.0";
    deviceInfo.event_time = NULL;
    deviceInfo.device_ip = NULL;
    deviceInfo.object_device_id = NULL;

    int messageId = IOTA_ReportBmsInfoTabAll(&deviceInfo);
    if (messageId == 0)
    {
        // DebugMsg("\r[long] mqtt report msg ok ...\n");
        sprintf(strline, "Repo-ok  "); 
    }
    else 
    {
        // DebugMsg("\r[long] mqtt report msg failed ...\n");
        sprintf(strline, "Repo-fail");
    }
    OledShowString(2, 6, strline, 1);
}

/**
 * @brief 
 * 
 */
void InitMqttClient(void)
{
    // 初始化并启动MQTT任务，连接MQTT服务器
    MqttTaskInit();                                                    // 初始化并启动MQTT任务

    const char *host = MQTT_SERVER_HOST;                               // MQTT服务器IP地址
    unsigned short port = atoi(MQTT_SERVER_PORT);                      // MQTT服务器端口
    const char *clientId = MQTT_CLIENTID;                              // MQTT客户端ID
    const char *username = MQTT_USERNAME;                              // MQTT服务器用户名
    const char *password = MQTT_PASSWORD;                              // MQTT服务器密码
    if (MqttTaskConnect(host, port, clientId, username, password) != 0) // 连接MQTT服务器
    {
        osal_printk("[long] Connect to MQTT server failed!\r\n");
        return;
    }

    // 订阅主题
    // MqttSubEntry();
    MqttTaskSubscribe(MQTT_SUBTOPIC_DOWN);
    MqttTaskSubscribe(MQTT_SUBTOPIC_SET);
    
    // 向主题 发布上线消息
    char *ptopic = MQTT_PUBTOPIC;          // 主题
    char *payload = "{\"device_id\":\"NearLink0001\", \"status\":\"online\"}";   // 消息内容
    int rc = MqttTaskPublish(ptopic, payload);                                   // 发布消息
    if (rc != 0)                                                                 // 检查是否成功发布消息
    {    
        osal_printk("\r[long] MQTT Publish online failed! \r\n");
    }
    else
    {
        osal_printk("\r[long] MQTT Publish online OK\r\n");
    }
}


/**
 * @brief 
 * 
 * @param args 
 * @return void* 
 */
void MqttReportThreadTask(void *args)
{
    InitMqttClient();

    while(1)
    {
        Mqtt_ReportBmsInfo_Handle();
        osDelay(100); 
    }
}

/**
 * @brief 
 * 
 */
void mqttClientCreate_TaskEntry(void)
{
    osThreadAttr_t attr = {0};
    attr.name = "mqtt Report";
    attr.stack_size = 1024 * 10;
    attr.priority = osPriorityNormal;
    
    if (osThreadNew(MqttReportThreadTask, NULL, &attr) == NULL)
    {
        osal_printk("[Error] Falied to create mqtt Report ...\n");
    }
}

